package com.feng.chat.service.impl;

import com.feng.chat.dto.Result;
import com.feng.chat.service.CommonService;
import com.feng.chat.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements CommonService {
//    @Autowired
//    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送邮箱验证码
     *
     * @param email
     * @param session
     * @return
     */
    @Override
    public Result emailCode(String email, HttpSession session) {
        if (email != null) {
            String code = String.format("%04d", new Random().nextInt(9999));
            MailUtil.sendMail(email, "你好，LumenIM邮箱验证码为:" + code + "，五分钟内有效。", "LumenIM邮箱验证");
//            session.setAttribute(email, code);
            // redis 存储验证码
            redisTemplate.opsForValue().set(email, code,5, TimeUnit.MINUTES);
//            session.setMaxInactiveInterval(5 * 60);
            return Result.success();
        }
        return Result.fail("请输入邮箱！");
    }


    /**
     * 发送手机验证码
     *
     * @param channel
     * @param mobile
     * @param session
     * @return
     */
    @Override
    public Result smsCode(String channel, String mobile, HttpSession session) {
        if (mobile != null && !mobile.equals("")) {
            String code = String.format("%04d", new Random().nextInt(9999));
//            session.setAttribute(mobile, code);
//            session.setMaxInactiveInterval(5 * 60);

            // redis 存储验证码
            redisTemplate.opsForValue().set(mobile, code,5, TimeUnit.MINUTES);
            Map<String, String> map = new HashMap<>();
            map.put("is_debug", "true");
            map.put("sms_code", code);
            return Result.success(map);
        }
        return Result.fail("请输入手机号！");
    }
}
